﻿// See https://aka.ms/new-console-template for more information
using Neoit.Utils.Extensions;
using System.Text.RegularExpressions;

Console.WriteLine("Hello, World!");




string html = @"
            <body>
                <if $='age==19'>
                    <div>dsd</div>
                    <if $='age==18'>a</if>
                    1900
                </if> 

                <if $='age==18'>
                    <div>dsd</div>
                    <if $='age==18'>
                        b
                    </if>
                </if>
                <div>xx</div>
            </body>";

var data = new ExampleData();
string parsedHtml = ConditionalParser.ParseIf(html, data);

Console.ReadKey();




public class ConditionalParser
{
    public static string ParseIf<T>(string html, T data)
    {
        return ParseRecursive(html, data);
    }

    private static string ParseRecursive<T>(string html, T data)
    {
        // Regex to match the most outer <if $='condition'>...</if> blocks
        var ifOuterRegex = new Regex(@"<if \$='([^']+)'>(((?!<if \$).)*?)<\/if>", RegexOptions.Singleline);

        // Find the next outermost <if> block
        var match = ifOuterRegex.Match(html);
        while (match.Success)
        {
            string condition = match.Groups[1].Value;
            string content = match.Groups[2].Value;

            // Recursively parse internal content
            content = ParseRecursive(content, data);

            // Evaluate the condition
            string replacement = EvaluateCondition(condition, data) ? content : string.Empty;

            // Replace the whole <if> block with content or empty string
            html = html.Substring(0, match.Index) + replacement + html.Substring(match.Index + match.Length);

            // Search for the next block
            match = ifOuterRegex.Match(html);
        }

        return html;
    }

    private static bool EvaluateCondition<T>(string condition, T data)
    {
        var parts = condition.Split(new[] { "==" }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2) return false;

        string propertyName = parts[0].Trim();
        string value = parts[1].Trim();

        // Using reflection to get the value of the property from data
        var propertyInfo = typeof(T).GetProperty(propertyName);
        if (propertyInfo == null) return false;

        var propertyValue = propertyInfo.GetValue(data)?.ToString();

        return propertyValue == value;
    }
}

// Example usage
public class ExampleData
{
    public int age { get; set; } = 18;
}



public class Stu
{
    public string Name { get; set; }
}
